package com.zhyl.demo.controller;

import com.zhyl.demo.entity.User;
import com.zhyl.demo.service.PatientService;
import com.zhyl.demo.service.UserService;
import com.zhyl.demo.utils.Result;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author yang3
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final PatientService patientService;

    @Autowired
    private UserController(UserService userService, PatientService patientService) {
        this.userService = userService;
        this.patientService = patientService;
    }

    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    @RequestMapping("/login")
    public Result login(String username, String password) {
        if (username == null || password == null) {
            return Result.error("-2", "请输入用户名和密码");
        }
        User user = userService.login(username.trim(), password.trim());
        if (user == null) {
            return Result.error("-1", "用户名或密码错误");
        }
        return Result.success(user);
    }

    @RequestMapping("/register")
    public Result register(@RequestBody User user) {
        if (user.getUsername().trim().isEmpty() || user.getPassword().trim().isEmpty()) {
            return Result.error("-1", "用户名或密码不能为空");
        }
        User isHave = selectByUsername(user.getUsername());
        if (isHave != null) {
            return Result.error("-1", "该用户已存在");
        } else {
            Boolean register = userService.register(user);
            if (register) {
                int pid = user.getId();
                if (user.getRole().equals("patient")) {
                    patientService.CreatePatient(pid);
                }
                return Result.success(user);
            } else {
                return Result.error("-1", "参数错误");
            }
        }

    }


    public User selectByUsername(String username) {
        if (username == null) {
            return null;
        }

        return userService.selectByUsername(username);
    }


    @PostMapping("/uploadFace")
    public Result uploadFace(@RequestBody Integer userId, @RequestParam("file") MultipartFile[] files) throws Exception {
        if (userId <= 0) {
            return Result.error("用户id不能为空...", "-1");
        }
        // 文件保存的命名空间
        String fileSpace = "C:/Users/yang3/Desktop/作业/毕设/Zh_medical/image";
        // 保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/face";

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            //如果微信端传来的头像不为空
            if (files != null && files.length > 0) {
                //获取文件名
                String fileName = files[0].getOriginalFilename();
                //如果文件名不为空
                if (fileName != null && !fileName.isEmpty()) {
                    // 文件上传的最终保存路径
                    String finalFacePath = fileSpace + uploadPathDB + "/" + fileName;
                    // 设置数据库保存的路径
                    uploadPathDB += ("/" + fileName);

                    File outFile = new File(finalFacePath);
                    //判断父文件夹是否存在
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        // 父文件夹不存在则创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }

                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }

            } else {
                return Result.error("上传出错...", "-1");
            }
        } catch (Exception e) {
            org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
            logger.error("Error occurred", e);
            return Result.error("上传出错...", "-1");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        User user=new User();
		user.setId(userId);
		user.setFaceImage(uploadPathDB);
		//修改用户信息
        Boolean b = userService.uploadFace(user);
        if (b){
            return Result.success(uploadPathDB);
        }else {
            return Result.error("上传失败","-1");
        }
    }

    @RequestMapping("/getUserInfo")
    public Result getUserInfo(Integer userId){
        if (userId==null){
            return Result.error("用户id不能为空","-1");
        }
        User user=userService.getUserInfo(userId);
        if (user!=null){
            return Result.success(user);
        }else {
            return Result.error("查询失败","-1");
        }
    }

    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        if (user==null){
            return Result.error("用户信息不能为空","-1");
        }
        Boolean b = userService.updateUser(user);
        if (b){
            return Result.success(null);
        }else {
            return Result.error("修改失败","-1");
        }

    }



    //生成随机八位数
    public static long getRandomNumber() {
        long currentTimeStamp = System.currentTimeMillis();
        String timeStampString = String.valueOf(currentTimeStamp);
        String lastEightDigits = timeStampString.substring(timeStampString.length() - 8);
        long lastEightDigitsLong = Long.parseLong(lastEightDigits);
        return lastEightDigitsLong % 100000000;
    }
}

